import jwt from 'jsonwebtoken';
import dataStore from '../data/mockData.js';

const JWT_SECRET = 'your-secret-key-change-in-production';

// JWT认证中间件
export const authMiddleware = (req, res, next) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问token不能为空'
      });
    }

    // 验证token
    const decoded = jwt.verify(token, JWT_SECRET);
    
    // 检查会话是否存在
    const session = dataStore.getSession(token);
    if (!session) {
      return res.status(401).json({
        success: false,
        message: 'Token无效或已过期'
      });
    }

    // 更新最后访问时间
    session.lastAccess = new Date();
    
    // 将用户信息添加到请求对象
    req.user = decoded;
    req.token = token;
    
    next();
  } catch (error) {
    console.error('认证错误:', error);
    
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        success: false,
        message: 'Token已过期，请重新登录'
      });
    }
    
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        success: false,
        message: 'Token无效'
      });
    }
    
    return res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
};

// 可选认证中间件（token可选）
export const optionalAuthMiddleware = (req, res, next) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (token) {
      const decoded = jwt.verify(token, JWT_SECRET);
      const session = dataStore.getSession(token);
      
      if (session) {
        session.lastAccess = new Date();
        req.user = decoded;
        req.token = token;
      }
    }
    
    next();
  } catch (error) {
    // 可选认证失败时不返回错误，继续执行
    next();
  }
};

// 角色权限中间件
export const roleMiddleware = (roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '需要登录'
      });
    }
    
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      });
    }
    
    next();
  };
};

// 管理员权限中间件
export const adminMiddleware = roleMiddleware(['admin']);

// 编辑器权限中间件
export const editorMiddleware = roleMiddleware(['admin', 'editor']);

// 速率限制中间件（简单实现）
const requestCounts = new Map();

export const rateLimitMiddleware = (limit = 100, windowMs = 15 * 60 * 1000) => {
  return (req, res, next) => {
    const ip = req.ip || req.connection.remoteAddress;
    const now = Date.now();
    const windowStart = now - windowMs;
    
    // 获取该IP的请求记录
    let requests = requestCounts.get(ip) || [];
    
    // 清理过期的请求记录
    requests = requests.filter(time => time > windowStart);
    
    // 检查是否超过限制
    if (requests.length >= limit) {
      return res.status(429).json({
        success: false,
        message: '请求过于频繁，请稍后再试',
        retryAfter: Math.ceil(windowMs / 1000)
      });
    }
    
    // 记录当前请求
    requests.push(now);
    requestCounts.set(ip, requests);
    
    next();
  };
};

// 清理过期会话的定时任务
setInterval(() => {
  dataStore.clearExpiredSessions();
}, 60 * 60 * 1000); // 每小时清理一次